<?php
if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

function get_vote_user(&$users){
	if (empty($users) || count($users) == 0){
		return ;
	}
	$ids = get_column_list($users, 'id');
	$sql = ' select * from '.DB::table('vote_user').' where id in ('.dimplode($ids).')';
	$vote_users = query($sql);
	$columns = array();
	if (count($vote_users) > 0) {
		foreach ($vote_users[0] as $key => $value) {
			$columns[] = $key;
		}
		$vote_users_map = get_column_map($vote_users, 'id');
		for($i = 0, $n = count($users); $i < $n; $i++ ) {
			foreach ($columns as $column) {
				$users[$i][$column] = $vote_users_map[$users[$i]['id']][$column];
			}
		}
	}
}

function get_user_count(&$users){
	if (empty($users) || count($users) == 0){
		return ;
	}
	$aid = $users[0]['aid'];
	$activity = get_activity($aid);
	$total_score = build_total_score_sql($activity['credits_rule']);
	$rank_sql = ' select  '.$total_score.' as total_score, uc.* from '.DB::table('vote_user_count').' uc ';
	$sql = ' select @rownum := @rownum + 1 as rank, a.* from ( '.$rank_sql.' ) a,(select @rownum := 0) r order by a.total_score desc';
	$users_count = query($sql);
	$users_count_map = get_column_map($users_count, 'id');
	for($i = 0, $n = count($users); $i < $n; $i++ ) {
		$users[$i]['rank'] = $users_count_map[$users[$i]['id']]['rank'];
		$users[$i]['total_score'] = $users_count_map[$users[$i]['id']]['total_score'];
		$users[$i]['bid_gold_coin'] = $users_count_map[$users[$i]['id']]['bid_gold_coin'];
		$users[$i]['member_tickets'] =$users_count_map[$users[$i]['id']]['member_tickets'];
		$users[$i]['ip_tickets'] = $users_count_map[$users[$i]['id']]['ip_tickets'];
	}
}

function get_user_pic(&$users){
	$picids = get_column_list($users, 'picid');
	$sql = ' select * from '.DB::table('home_pic').' where picid in ('.dimplode($picids).')';
	$pics = query($sql);
	$pics_map = get_column_map($pics, 'picid');
	for($i = 0, $n = count($users); $i < $n; $i++ ) {
		$users[$i]['pic'] = $pics_map[$users[$i]['picid']];
	}
}

function check_entry_status($activity, $entry_activities){
	if (empty($entry_activities) || count($entry_activities) == 0) {
		return true;
	}

	foreach ($entry_activities as $tmp) {
		if (($activity['bid_start_day'] >= $tmp['bid_start_day'] && $activity['bid_start_day'] <= $tmp['bid_end_day'])
			|| ($activity['bid_end_day'] >= $tmp['bid_start_day'] && $activity['bid_end_day'] <= $tmp['bid_end_day'])) {
			return false;	
		}
	}
	return true;
}

function check_ip_tickets($ip, $aid, $uid){
	// 本次活动中用户投票总数
	$total_tickets = getcount('vote_ip_tickets', array('ip' => $ip, 'aid' => $aid) );
	$tickets_ip_day = getcount('vote_ip_tickets', array('ip' => $ip, 'aid' => $aid, 'ticket_time' => today()) );
	$activity = get_activity($aid);

	$result = 0;
	if ($activity['max_tickets_ip'] <= $total_tickets ) {
		$result -= 1;
	}
	if ($activity['max_tickets_ip_day'] <= $tickets_ip_day) {
		$result -= 2;
	}
	return array($result, $total_tickets, $tickets_ip_day);
}

function vote_ip_tickets($ip, $aid, $uid){
	list($result, $total_tickets, $user_ip_tickets) = check_ip_tickets($ip, $aid, $uid);
	if (0 == $result){
		$count = DB::insert('vote_ip_tickets', array('ip' => $ip, 'aid' => $aid, 'uid' => $uid, 'ticket_time' => today()), true, false, true);

		// 更新 vote_user_count 表
		$sql = ' SELECT count(*) as  ip_tickets FROM  '.DB::table('vote_ip_tickets')." where ip = '$ip'".' and uid = '.$uid;
		$row = DB::fetch_first($sql);
		DB::update('vote_user_count', array('ip_tickets' => $row['ip_tickets']), array('aid' => $aid, 'uid' => $uid));
	}
	return array($result, $total_tickets, $user_ip_tickets);
}

function build_rank_sql($activity){
	$sql = 'select @rownum := @rownum + 1 as rank, a.* from (select #TOTAL_SCORE# as total_score, uc.* from pre_vote_user_count uc  ) a,(select @rownum := 0) r
		where a.aid = #AID# order by a.total_score desc ';

	$sql = str_replace('#TOTAL_SCORE#', $activity['total_socre_formula'], $sql);
	$sql = str_replace('#AID#', $activity['id'], $sql);
	return $sql;
}

function build_total_score_sql($credits_rule){
	if (empty($credits_rule)) {
		$credits_rule = 'bid_gold_coin + member_tickets * 2 + ip_tickets';
	}
	$credits_rule = str_replace('竞标金币数', 'bid_gold_coin', $credits_rule);
	$credits_rule = str_replace('会员投票数', 'member_tickets', $credits_rule);
	$credits_rule = str_replace('独立IP投票数', 'ip_tickets', $credits_rule);
	$credits_rule = str_replace('×', '*', $credits_rule);
	$credits_rule = str_replace('＋', '+', $credits_rule);
	$credits_rule = str_replace('（', '(', $credits_rule);
	$credits_rule = str_replace('）', ')', $credits_rule);
	return ' ('.$credits_rule.') ';
}
/**
 *
 * 会员投票.
 *
 * @param $mid
 * 	投票会员的唯一标识
 * @param $aid
 * 	活动的唯一标识
 * @param $uid
 * 	参赛选手的唯一标识
 */
function vote_member_tickets($mid, $aid, $uid){
	$activity = get_activity($aid);
	list($result, $total_tickets, $user_member_tickets) = check_member_tickets($mid, $aid, $uid);
	if (0 == $result){
		$count = DB::insert('vote_member_tickets', array('mid' => $mid, 'aid' => $aid, 'uid' => $uid, 'ticket_time' => today()), true, false, true);

		// 扣减金币。更新参赛人数
		updatemembercount($_G['uid'], array(get_gold_coin_field() => (0 - $activity['ticket_fee'])), true, 'TIK', $_G['uid']);

		// 更新 vote_user_count 表
		$member_tickets = getcount('vote_member_tickets', array('uid' => $uid, 'aid' => $aid));
		DB::update('vote_user_count', array('member_tickets' => $member_tickets), array('aid' => $aid, 'uid' => $uid));
	}
	return array($result, $total_tickets, $user_member_tickets);
}

/**
 *
 * 检查当前用户是否能够正常投票．正常投票的几个条件：
 * <ul>
 * 	<li>投票总数不能超过，该活动规定的单个会员最大投票数。</li>
 * 	<li>针对单个参赛选手投票数，不能超过该活动规定的单个会员针对单个选手的最大投票数。</li>
 * </ul
 */
function check_member_tickets($mid, $aid, $uid){
	// 本次活动中用户投票总数
	
	$total_tickets = getcount('vote_member_tickets', array('mid' => $mid, 'aid' => $aid));
	$tickets_member_day = getcount('vote_member_tickets', array('mid' => $mid, 'aid' => $aid, 'ticket_time' => today()));
	
	$activity = get_activity($aid);
	$result = 0;
	if ($activity['max_tickets_member'] <= $total_tickets ) {
		$result -= 1;
	}
	if ($activity['max_tickets_member_day'] <= $tickets_member_day) {
		$result -= 2;
	}
	return array($result, $total_tickets, $tickets_member_day);
}

function get_user($uid, $force = false){
	$user = memory('get', 'vote_user_'.$uid);
	if (!$force && !empty($user)){
		return $user;
	}
	$user = fetch_first('vote_user', array('uid' => $uid));
	memory('set', 'vote_user_'.$uid, $user);
	return $user;
}
/**
 *
 * 读取指定ID的活动信息
 *
 * @param $aid
 * 	活动的唯一标识
 */
function get_activity($aid){
	$activities = memory('get', 'activities');
	$activity = get_row($activities, $aid);
	if (!empty($activity)){
		return $activity;
	}

	$activity = fetch_first('vote_activity', array('id' => $aid));
	if (!empty($activity)){
		$activities[] = $activity;
		memory('set', 'activities', $activities);
	}
	return $activity;
}



function get_activity_count(&$activity){
	$tmp = array($activity);
	get_activities_count($tmp);
	$activity = $tmp[0];
}

function get_activities_count(&$activities){
	if (empty($activities) || count($activities) == 0){
		return ;
	}

	$ids = get_column_list($activities, 'id');
	$sql = ' select * from '.DB::table('vote_activity_count').' where id in ('.dimplode($ids).')';
	$activities_count = query($sql);
	$activities_count_map = get_column_map($activities_count, 'id');
	for($i = 0, $n = count($activities); $i < $n; $i++ ) {
		$activities[$i]['user_count'] = $activities_count_map[$activities[$i]['id']]['user_count'];
		$activities[$i]['participation_count'] = $activities_count_map[$activities[$i]['id']]['participation_count'];
	}
}

function get_gold_coin_field(){
	return 'extcredits2';
}
/**
 *
 * 读取当前用户拥有的金币数量。
 */
function get_gold_coin(){
	return getuserprofile(get_gold_coin_field());
}

/**
 * 检查用户是否满足参加报名的条件。
 */
function check_entry_submit($user_gold_coin, $activity_gold_coin){
	return $user_gold_coin > $activity_gold_coin;
}


function get_default_credits_rule(){
	return ' 竞标金币数  × 2 + 会员投票数 × 5 + 独立IP投票数 ';
}
/**
 * 统计参赛选手得分。
 *
 * @param $vote_user
 * 	参赛选手信息
 * @param $credits_rule
 *  like 竞标金币数 × 2 + 会员投票数 × 5 + 独立IP投票数
 */
function calc_score($vote_user, $credits_rule){
	$credits_rule = str_replace('竞标金币数', $vote_user['bid_gold_coin'], $credits_rule);
	$credits_rule = str_replace('会员投票数', $vote_user['member_tickets'], $credits_rule);
	$credits_rule = str_replace('独立IP投票数', $vote_user['ip_tickets'], $credits_rule);
	$credits_rule = str_replace('×', '*', $credits_rule);
	$credits_rule = str_replace('＋', '+', $credits_rule);
	$credits_rule = str_replace('（', '(', $credits_rule);
	$credits_rule = str_replace('）', ')', $credits_rule);
	return eval('return '.$credits_rule.';');
}
/**
 * 创建首页竞秀活动。
 *
 * @param int $start_days 用秒表示的日期
 */
function create_activity($start_days){
	if (empty($start_days)) {
		return null;
	}

	$activity = array();
	$activity['name'] = $activity['description'] = get_activity_name($start_days);
	$activity['status'] = 0;
	$activity['img_start_day'] = $start_days;
	$activity['img_end_day'] = ($start_days + 6 * 86400);
	$activity['bid_start_day'] = ($start_days - 28 * 86400);
	$activity['bid_end_day'] = ($start_days - 1 * 86400);
	$activity['insert_time'] = $activity['update_time'] = time();
	return $activity;
}

function format_activity($activity){
	$activity['img_start_day_string'] = date('Y年m月d日', $activity['img_start_day']);
	$activity['img_end_day_string'] = date('Y年m月d日', $activity['img_end_day']);
	$activity['bid_start_day_string'] = date('Y年m月d日', $activity['bid_start_day']);
	$activity['bid_end_day_string'] = date('Y年m月d日', $activity['bid_end_day']);
	$activity['total_socre_formula'] = build_total_score_sql($activity['credits_rule']);
	$activity['cache_time'] = time();
	if (0 == $activity['status']){
		$activity['status_string'] = '可编辑';
	} else if (1 == $activity['status']){
		$activity['status_string'] = '报名中';
	} else if (2 == $activity['status']){
		$activity['status_string'] = '竞拍中';
	} else if (3 == $activity['status']){
		$activity['status_string'] = '已关闭';
	}
}
/**
 * 针对活动进行转化处理，主要格式化字符床、状态类型等等字段。
 * @param $activities
 */
function format_activities(&$activities){
	for ($i = 0, $n = count($activities); $i < $n; $i++ ){
		format_activity($activities[$i]);
	}
}


/**
 * 根据照片展示日期生成活动名称。
 *
 * @param $start_days
 * 			用秒表示的开始日期
 * @param $end_days
 * 			用秒表示的结束日期
 */
function get_activity_name($start_days, $end_days = ''){
	if (empty($start_days)) {
		return '';
	}
	if (empty($end_days)) {
		$end_days = ($start_days + 6 * 86400);
	}
	return (date('Y', $start_days).'年 第'.date('W', $start_days).'周首页竞秀');
}

function get_activities($start_date = ''){
	$img_start_days = array();
	$activities = array();
	if(empty($start_date)){
		$next_sunday = dweek('+7 days');
		$start_date = "$next_sunday +28 days";
	}
	$start_days =  strtotime($start_date);
	for($i = 0; $i < 12; $i++) {
		$activities[] = array('value' => $start_days, 'label' => get_activity_name($start_days));
		$img_start_days[] = $start_days;

		$start_days += (7 * 86400); // +7 days
	}
	return array($img_start_days, $activities);
}

function get_year_month_day($date_value = ''){
	$date = date();
	if (!empty($date_value)) {
		$date = strtotime($date_value);
	}
	return array(date('Y', $date), date('m', $date), date('d', $date));
}

?>